package aar.test.tessocr;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import aar.test.tessocr.EventMessage.EventMessage;
import aar.test.tessocr.base.BaseActivity;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.db.impl.ClientInfoDaoImp;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.OrderPayModel;
import aar.test.tessocr.model.loginModel;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.PrefUtils;
import aar.test.tessocr.utils.Urls;
import aar.test.tessocr.utils.Utils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import clx.tessocr.ocreng.R;
import okgo.OkGo;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.Login1Activity.JSON;

/**
 * Created by sunshine on 2020/7/30
 */
public class PayActivity extends BaseActivity {
    @BindView(R.id.txt_account)
    TextView txtAccount;
    @BindView(R.id.txt_10)
    TextView txt10;
    @BindView(R.id.txt_20)
    TextView txt20;
    @BindView(R.id.txt_30)
    TextView txt30;
    @BindView(R.id.txt_50)
    TextView txt50;
    @BindView(R.id.txt_100)
    TextView txt100;
    @BindView(R.id.txt_other)
    TextView txtOther;
    @BindView(R.id.title_content)
    EditText titleContent;
    @BindView(R.id.rl_define)
    RelativeLayout rlDefine;

    String payStr = "";
    private boolean isOther = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        ButterKnife.bind(this);
        initView();
        /*if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }*/
    }

    private void initView() {
        //txtAccount.setText(BaseApplication.getIntance().getLoginBean().getUsername());
        txtAccount.setText(PrefUtils.getString(PayActivity.this, "userName", ""));
        payStr = "10";
    }

    @OnClick({R.id.left_layout, R.id.txt_10, R.id.txt_20, R.id.txt_30, R.id.txt_50, R.id.txt_100, R.id.txt_other, R.id._btn_charge})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_layout:
                finish();
                break;
            case R.id.txt_10:
                reset();
                txt10.setBackgroundResource(R.drawable.back_red);
                txt10.setTextColor(getResources().getColor(R.color.title_background_color));
                //titleContent.setText("10");
                payStr = "10";
                break;
            case R.id.txt_20:
                reset();
                txt20.setBackgroundResource(R.drawable.back_red);
                txt20.setTextColor(getResources().getColor(R.color.title_background_color));
                //titleContent.setText("20");
                payStr = "20";
                break;
            case R.id.txt_30:
                reset();
                txt30.setBackgroundResource(R.drawable.back_red);
                txt30.setTextColor(getResources().getColor(R.color.title_background_color));
                //titleContent.setText("30");
                payStr = "30";
                break;
            case R.id.txt_50:
                reset();
                txt50.setBackgroundResource(R.drawable.back_red);
                txt50.setTextColor(getResources().getColor(R.color.title_background_color));
                //titleContent.setText("50");
                payStr = "50";
                break;
            case R.id.txt_100:
                reset();
                txt100.setBackgroundResource(R.drawable.back_red);
                txt100.setTextColor(getResources().getColor(R.color.title_background_color));
                //titleContent.setText("100");
                payStr = "100";
                break;
            case R.id.txt_other:
                reset();
                isOther = true;
                txtOther.setBackgroundResource(R.drawable.back_red);
                txtOther.setTextColor(getResources().getColor(R.color.title_background_color));
                rlDefine.setVisibility(View.VISIBLE);
                titleContent.setText("");
                payStr = "";
                break;
            case R.id._btn_charge:
                if (isOther) {
                    if (titleContent.getText().toString().trim().equals("0") || titleContent.getText().toString().trim().equals("")) {
                        Toast.makeText(this,"金额必须为大于0的整数",Toast.LENGTH_SHORT).show();
                        return;
                    }

                    payStr = titleContent.getText().toString().trim();
                }

                Map<String ,Object> map=new HashMap<>();
                map.put("adminid",PrefUtils.getString(this, "userId", ""));
                map.put("money",payStr);

                Gson gg=new Gson();
                String json =gg.toJson(map);

                RequestBody body = RequestBody.create(JSON,json);
                OkGo.<LzyResponse<OrderPayModel>>post(Urls.URL_CHARGE)//
                        .tag(this)//
                        .upRequestBody(body)
                        .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                        .execute(new DialogCallback<LzyResponse<OrderPayModel>>(PayActivity.this) {
                            @Override
                            public void onSuccess(Response<LzyResponse<OrderPayModel>> response) {
                                IWXAPI api = WXAPIFactory.createWXAPI(PayActivity.this, null);
                                api.registerApp("wx8890d06ae86d3400");
                                if(!api.isWXAppInstalled()){
                                    Toast.makeText(PayActivity.this, "未安装微信", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                if (api.getWXAppSupportAPI() < Build.PAY_SUPPORTED_SDK_INT) {
                                    Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                PayReq req = new PayReq();
                                OrderPayModel orderPayModel = new OrderPayModel();
                                orderPayModel = response.body().data;
                                req.appId = orderPayModel.getAppid();
                                //req.appId = "wx8890d06ae86d3400";
                                req.partnerId = orderPayModel.getPartnerid();
                                req.prepayId = orderPayModel.getPrepayid();
                                req.nonceStr = orderPayModel.getNoncestr();
                                req.timeStamp = orderPayModel.getTimestamp();
                                req.packageValue = "Sign=WXPay";//固定值
                                req.sign = orderPayModel.getSign();
                                api.sendReq(req);
                            }

                            @Override
                            public void onError(Response<LzyResponse<OrderPayModel>> response) {
                                Toast.makeText(getApplicationContext(), "创建订单失败！", Toast.LENGTH_SHORT).show();


                            }
                        });
                break;
        }
    }

    private void reset() {
        txt10.setBackground(null);
        txt20.setBackground(null);
        txt30.setBackground(null);
        txt50.setBackground(null);
        txt100.setBackground(null);
        txtOther.setBackground(null);
        txt10.setTextColor(getResources().getColor(R.color.contents_text));
        txt20.setTextColor(getResources().getColor(R.color.contents_text));
        txt30.setTextColor(getResources().getColor(R.color.contents_text));
        txt50.setTextColor(getResources().getColor(R.color.contents_text));
        txt100.setTextColor(getResources().getColor(R.color.contents_text));
        txtOther.setTextColor(getResources().getColor(R.color.contents_text));
        rlDefine.setVisibility(View.GONE);
        isOther = false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShutDown(EventMessage eventMsg) {
        String msg = eventMsg.getMessage();
        if (msg.equals("shutDownPay")) {
            finish();
        }
    }

    /*@Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }*/
}
